package com.request.service.impl.shop.hf;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.request.common.constants.RedisConstant;
import com.request.common.enums.HfOrderStatusEnum;
import com.request.common.enums.RechargeTypeEnum;
import com.request.common.utils.HttpUtils;
import com.request.entity.PhoneOrderWaitCheck;
import com.request.service.QueryOrderProcessor;
import com.request.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Description:
 * Create DateTime: 2020/5/22 10:54
 *
 * 

 */
@Slf4j
@Service
public class HfQueryOrderProcessor implements QueryOrderProcessor {

    @Resource
    private RedisService redisService;

    @Resource
    private ThreadPoolExecutor handlerOrderExecutor;

    @Override
    public void sendRequest(PhoneOrderWaitCheck orderWaitCheck) {
        handlerOrderExecutor.execute(() -> executeWaitOrderQuery(orderWaitCheck));
    }

    /**
     * 执行待查询订单查询
     */
    private void executeWaitOrderQuery(PhoneOrderWaitCheck phoneOrderWaitCheck) {
        Map<String, Object> params = new HashMap<>(2);
        String result = null;
        try {
            String querySite = phoneOrderWaitCheck.getQuerySite();
            String platformOrderNo = phoneOrderWaitCheck.getPlatformOrderNo();

            params.put("cpparam", platformOrderNo);

            result = sendRequestForWaitOrder(querySite, params);
            log.info("【Hf】【查单】结果:{}", result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            Integer orderStatus = Integer.valueOf(jsonObject.getString("status"));
            String message = jsonObject.getString("message");
            if (null != jsonObject.getString("order_no")) {
                String orderSn = jsonObject.getString("order_no");
                phoneOrderWaitCheck.setOrderSn(orderSn);
            }
            if (null != jsonObject.getString("spref_url")) {
                String certificate = jsonObject.getString("spref_url");
                phoneOrderWaitCheck.setCertificate(certificate);
            }

            HfOrderStatusEnum hfOrderStatusEnum = HfOrderStatusEnum.getByCode(orderStatus);
            if (HfOrderStatusEnum.getByCode(orderStatus) == null) {
                throw new RuntimeException("订单相应失败,返回结果为:" + message);
            }
            switch (hfOrderStatusEnum) {
                case SUCCESS:
                    phoneOrderWaitCheck.setStatus(1);
                    saveWaitOrderQueryForSuccess(phoneOrderWaitCheck);
                    break;
                case FAILED:
                    phoneOrderWaitCheck.setStatus(0);
                    saveWaitOrderQueryForSuccess(phoneOrderWaitCheck);
                    break;
                case TIMEOUT:
                case PROCESSING:
                    if ("订单不存在".equals(message)) {
                        log.info("【Hf】【超时检查】订单不存在，查询的订单号为：{}, 响应的状态为：{}, 信息为：{}", platformOrderNo, orderStatus, message);
                        phoneOrderWaitCheck.setStatus(0);
                        saveWaitOrderQueryForSuccess(phoneOrderWaitCheck);
                        break;
                    }
                case CHARGING:
                    saveWaitOrderQueryForProcessing(phoneOrderWaitCheck);
                    break;
                default:
                    saveWaitOrderQueryForProcessing(phoneOrderWaitCheck);
                    break;
            }
        } catch (Exception e) {
            saveWaitOrderQueryForProcessing(phoneOrderWaitCheck);
            log.error("【Hf】【超时检查】请求商户出现异常，待检查订单信息为：{}, 参数为：{}, 响应结果为:{}, 详情为：{}",
                    phoneOrderWaitCheck, params.toString(), result, e);
        }

    }

    /**
     * 放入失败队列(废弃)
     * 原因：该处理状态在hf通道中弃用
     */
    @Deprecated
    private void saveWaitOrderQueryForFailed(PhoneOrderWaitCheck phoneOrderWaitCheck) {
        redisService.lPush(RedisConstant.PUSH_ORDER_WAIT_CHECK_FAILED, JSON.toJSONString(phoneOrderWaitCheck));
    }

    /**
     * 放入成功队列
     */
    private void saveWaitOrderQueryForSuccess(PhoneOrderWaitCheck phoneOrderWaitCheck) {
        redisService.lPush(RedisConstant.PUSH_ORDER_WAIT_CHECK_SUCCESS, JSON.toJSONString(phoneOrderWaitCheck));
    }

    private String sendRequestForWaitOrder(String url, Map<String, Object> params) {
        return HttpUtils.doPost(url, params);
    }

    /**
     * 放入处理中队列
     */
    private void saveWaitOrderQueryForProcessing(PhoneOrderWaitCheck phoneOrderWaitCheck) {
        if (!RechargeTypeEnum.SLOW.getCode().equals(phoneOrderWaitCheck.getRechargeType())) {
            redisService.lPush(RedisConstant.PUSH_ORDER_WAIT_CHECK_PROCESSING, JSON.toJSONString(phoneOrderWaitCheck));
        }
    }
}
